package test

import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel


class Server {

    fun start(beginPort: Int, nPort: Int) {
        println("server starting....")

        val bossGroup = NioEventLoopGroup()
        val workerGroup = NioEventLoopGroup()

        val bootstrap = ServerBootstrap()
        bootstrap.group(bossGroup, workerGroup)
        bootstrap.channel(NioServerSocketChannel::class.java)
        bootstrap.childOption(ChannelOption.SO_REUSEADDR, true)

        bootstrap.childHandler(object : ChannelInitializer<SocketChannel>() {
            @Throws(Exception::class)
            override fun initChannel(ch: SocketChannel) {
                //每个连接都有个ConnectionCountHandler对连接记数进行增加
                ch.pipeline().addLast(ConnectionCountHandler())
            }
        })

        //这里开启 10000到100099这100个端口
        for (i in 0 until nPort) {
            val port = beginPort + i
            bootstrap.bind(port)
                .addListener { future ->
                    println("bind success in port: $port")
                }
        }
        println("server started!")
    }
}